 ///
 /// @file    Computer.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-20 18:05:03
 ///
 
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer
{//class的默认访问权限是private的
public:
	Computer(const char * brand, float price)
	: _brand(new char[strlen(brand) + 1]())
	, _price(price)
	{
		cout << "Computer(const char*, float)" << endl;
		strcpy(_brand, brand);
	}

	//系统提供的不再满足需求
#if 0
	Computer(const Computer & rhs)
	: _brand(rhs._brand)
	, _price(rhs._price)
	{	cout << "Computer(const Computer&)" << endl;	}
#endif

	Computer(const Computer & rhs)
	: _brand(new char[strlen(rhs._brand) + 1]())
	, _price(rhs._price)
	{	
		cout << "Computer(const Computer&)" << endl;	
		strcpy(_brand, rhs._brand);
	}

	void print();

	//系统自动提供的析构函数无法解决问题了
	~Computer()
	{
		cout << "~Computer()" << endl;
		if(_brand) {
			//Safe delete操作
			delete [] _brand;
			_brand = nullptr;
		}
	}

private:
	char * _brand;
	float _price;
};
 
/* 隐含的this指针的形式: Computer * const this  */
void Computer::print() 
{
	//this = 1000;
	printf("brand字符串的地址: %p\n", _brand);
	cout << "brand:" << this->_brand << endl;
	cout << "price:" << this->_price << endl;
}

void test0() 
{
	Computer pc("Xiaomi", 7777);//pc称为对象
	cout << "pc:";
	pc.print();//=>  pc.print(&pc);  => Computer::print(&pc)

	cout << endl;
	Computer pc2 = pc;//调用拷贝构造函数进行复制

	cout << "pc2:";
	pc2.print();//=> pc2.print(&pc2);


	Computer pc3("Huawei", 8888);
	pc3.print();

} 
 
int main(void)
{
	test0();
	return 0;
}
